package com.coding.springboot.demo.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import com.coding.springboot.demo.entity.AccessToken;
import com.coding.springboot.demo.entity.TservicenoSet;
import com.coding.springboot.demo.entity.Twxuser;
import com.coding.springboot.demo.service.TservicenoSetService;
import com.coding.springboot.demo.service.TwxuserService;

import javax.servlet.http.HttpServletRequest;

import com.coding.springboot.demo.util.CommonUtil;
import com.coding.springboot.demo.util.Sign;
import com.coding.springboot.demo.util.WeixinUtil;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/wxutil")
public class WxUtilContrller {
	@Autowired
	private TservicenoSetService tservicenoSetService;
	@Autowired
	private TwxuserService twxuserService;

	@RequestMapping(value="/getAppid")
	@ResponseBody
	public JSONObject getAppid(HttpServletRequest request){
		JSONObject result = new JSONObject();
		String generalid_str = request.getParameter("generalid");
		if(StringUtils.isNotBlank(generalid_str)){
			Long generalid = Long.parseLong(generalid_str);
			if(generalid != null){
				TservicenoSet serviceno = tservicenoSetService.getServiceNo(generalid);
				if(serviceno != null){
					result.put("appid", serviceno.getAppid());
				}else{
					result.put("errcode", "01");
					result.put("errmsg", "公众号未设置APPID和APPSECRET!");
				}
			}else{
				result.put("errcode", "01");
				result.put("errmsg", "公众号不存在!");
			}
		}else{
			result.put("errcode", "01");
			result.put("errmsg", "参数错误!");
		}

		return result;
	}


	@RequestMapping(value="/getUserInfo")
	@ResponseBody
	public JSONObject getUserInfo(HttpServletRequest request){
		JSONObject result = new JSONObject();
		String code = request.getParameter("code");
		String generalid_str = request.getParameter("generalid");
		if(StringUtils.isBlank(generalid_str)){
			result.put("errcode", "02");
			result.put("errmsg", "参数错误!");
			return result;
		}
		Long generalid = Long.parseLong(generalid_str);
		TservicenoSet serviceno = tservicenoSetService.getServiceNo(generalid);
		if(serviceno == null){
			result.put("errcode", "02");
			result.put("errmsg", "公众号未设置APPID和APPSECRET!");
			return result;
		}
		String appid = serviceno.getAppid();
		String secret = serviceno.getAppsecret();
		JSONObject token = WeixinUtil.getToken(appid, secret, code);
		if(token.get("errcode") != null){
			return token;
		}else{
			//String access_token = token.getString("access_token");
			String openid = token.getString("openid");
			result.put("openid", openid);
			// result = WeixinUtil.getUserInfo(access_token, openid);
			//System.out.println(result);
		}
		return result;
	}


	@RequestMapping(value="/getWxConfig")
	@ResponseBody
	public Map<String, String> getWxConfig(HttpServletRequest request){
		Map<String, String> result = new HashMap<String, String>();
		String url = request.getParameter("url");
		String generalid_str = request.getParameter("generalid");
		Long generalid = Long.parseLong(generalid_str);
		TservicenoSet serviceno = tservicenoSetService.getServiceNo(generalid);
		if(serviceno == null){
			result.put("errcode", "02");
			result.put("errmsg", "公众号未设置APPID和APPSECRET!");
			return result;
		}
		String flag="";
		String appid = serviceno.getAppid();
		String secret = serviceno.getAppsecret();
		String jsapi_ticket=serviceno.getJsapiTicket();
		Date now = new Date();
		Long l = CommonUtil.compareTime(serviceno.getGettokentime(), now);
		if ((CommonUtil.isNotNull(serviceno.getToken()) && l >= 2 * 60 * 60)//token不为空 且过期了
				|| (CommonUtil.isNull(serviceno.getToken())) ) {//token为空
			AccessToken accessToken=WeixinUtil.getAccessToken(appid, secret);
			if(CommonUtil.isNotNull(accessToken)){
				serviceno.setToken(accessToken.getToken());
				serviceno.setGettokentime(now);
				flag="0";
			}
		}
		Date _now = new Date();
		Long _l = CommonUtil.compareTime(serviceno.getGettickettime(), _now);
		if((CommonUtil.isNull(jsapi_ticket)) || (CommonUtil.isNotNull(jsapi_ticket) && _l >= 2 * 60 * 60) ){
			JSONObject jsonObject  = WeixinUtil.getJsapiUrl(serviceno.getToken());
			jsapi_ticket=(String) jsonObject.get("ticket");
			serviceno.setJsapiTicket(jsapi_ticket);
			serviceno.setGettickettime(_now);
			flag="1";
		}
		if(CommonUtil.isNotNull(flag)){
			tservicenoSetService.save(serviceno);
		}
		Map<String, String> ret = Sign.sign(jsapi_ticket, url);
		ret.put("appId", appid);
		return ret;
	}

	@RequestMapping(value="/getWxUserInfo")
	@ResponseBody
	public JSONObject getWxUserInfo(HttpServletRequest request){
		JSONObject result = new JSONObject();
		String code = request.getParameter("code");
		String generalid_str = request.getParameter("generalid");
		if(CommonUtil.isNull(generalid_str)){
			result.put("errcode", "02");
			result.put("errmsg", "参数错误!");
			return result;
		}
		Long generalid = Long.parseLong(generalid_str);
		TservicenoSet serviceno = tservicenoSetService.getServiceNo(generalid);

		String appid = serviceno.getAppid();
		String secret = serviceno.getAppsecret();
		JSONObject token = WeixinUtil.getToken(appid,secret,code);
		if(token.get("errcode") != null){
			return token;
		}else{
			String access_token = token.getString("access_token");
			String openid = token.getString("openid");
			result = WeixinUtil.getUserInfo(access_token, openid);
			if(result.get("errcode") == null){
				String _nickname = "";
				if (result.get("nickname") != null)
					_nickname =result.getString("nickname");
				StringBuilder _sb = new StringBuilder();
				int _l = _nickname.length();
				for (int i = 0; i < _l; i++) {
					char _s = _nickname.charAt(i);
					if (isEmojiCharacter(_s)) {
						_sb.append(_s);
					}
				}
				result.put("nickname", _sb.toString());
				Twxuser twxuser = twxuserService.getByWxno(openid);
				if(CommonUtil.isNull(twxuser)){
					twxuser = new Twxuser();
					twxuser.setNickname(_sb.toString());
					twxuser.setPhotourl(result.getString("headimgurl"));
					twxuser.setCreatetime(new Date());
					twxuser.setGeneralid(1l);
					twxuser.setWxno(result.getString("openid"));
					twxuserService.save(twxuser);
				}
			}

		}
		return result;
	}


	private static boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) ||

				(codePoint == 0x9) ||

				(codePoint == 0xA) ||

				(codePoint == 0xD) ||

				((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||

				((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||

				((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));

	}
}
